// 定义 Pinia store
import { ref } from 'vue'
import { message } from 'ant-design-vue'
import { defineStore } from 'pinia'
import { getTokenApi, getUserInfoApi } from '@/api/modules/base'

export default defineStore('counter', () => {
  const getToken = () => sessionStorage.getItem('token')
  const getUserInfo = () => JSON.parse(sessionStorage.getItem('userInfo') ?? '{}')

  const token = ref(getToken() ?? undefined)
  const user = ref(getUserInfo())
  const isLoggedIn = ref(token.value !== undefined)

  const login = async (userName: string, password: string) => {
    try {
      const res = await getTokenApi({
        userName,
        password,
        clientId: 'admin-client-demo',
        clientSecret: '1q2w3e*',
        remember: true,
        mode: 'none'
      })
      if (res.access_token) {
        token.value = `Bearer ${res.access_token}`
        sessionStorage.setItem('token', `Bearer ${res.access_token}`)
        user.value = await getUserInfoApi()
        sessionStorage.setItem('userInfo', JSON.stringify(user.value))
        message.success('登录成功')
        isLoggedIn.value = true
      } else {
        logout(false)
      }
    } catch {
      isLoggedIn.value = false
      message.success('登录失败')
      logout(false)
    }
  }
  const logout = (msg = true) => {
    token.value = undefined
    user.value = undefined
    isLoggedIn.value = false
    sessionStorage.removeItem('token')
    sessionStorage.removeItem('userInfo')
    msg && message.success('注销成功')
  }

  return { user, token, isLoggedIn, login, logout, getToken, getUserInfo }
})
